package com.yuelife.user.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.yuelife.user.entity.Village;
import com.yuelife.user.pojo.Home;
import com.yuelife.user.pojo.User;
import com.yuelife.user.service.HomeService;
import com.yuelife.user.service.UserService;
import com.yuelife.user.service.VillageService;
import com.yuelife.user.utils.AliyunossUtils;
import com.yuelife.user.utils.FileUploadResult;
import entity.JwtUtil;
import entity.Result;
import entity.ResultUtil;
import entity.StatusCode;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/****
 * @Author:admin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@Api(value = "UserController")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private AliyunossUtils aliyunossUtils;
    @Autowired
    private HomeService homeService;
    @Autowired
    private VillageService villageService;

    /***
     * User分页条件搜索实现
     * @param user
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "User条件分页查询",notes = "分页条件查询User方法详情",tags = {"UserController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false) @ApiParam(name = "User对象",value = "传入JSON数据",required = false) User user, @PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页条件查询User
        PageInfo<User> pageInfo = userService.findPage(user, page, size);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * User分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @ApiOperation(value = "User分页查询",notes = "分页查询User方法详情",tags = {"UserController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页查询User
        PageInfo<User> pageInfo = userService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param user
     * @return
     */
    @ApiOperation(value = "User条件查询",notes = "条件查询User方法详情",tags = {"UserController"})
    @PostMapping(value = "/search" )
    public Result<List<User>> findList(@RequestBody(required = false) @ApiParam(name = "User对象",value = "传入JSON数据",required = false) User user){
        //调用UserService实现条件查询User
        List<User> list = userService.findList(user);
        return new Result<List<User>>(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @ApiOperation(value = "User根据ID删除",notes = "根据ID删除User方法详情",tags = {"UserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        //调用UserService实现根据主键删除
        userService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 修改User数据
     * @param user
     * @param id
     * @return
     */
    @ApiOperation(value = "User根据ID修改",notes = "根据ID修改User方法详情",tags = {"UserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @PutMapping(value="/{id}")
    public Result update(@RequestBody @ApiParam(name = "User对象",value = "传入JSON数据",required = false) User user,@PathVariable Integer id){
        //设置主键值
        user.setId(id);
        //调用UserService实现修改User
        userService.update(user);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /***
     * 新增User数据
     * @param user
     * @return
     */
    @ApiOperation(value = "User添加",notes = "添加User方法详情",tags = {"UserController"})
    @PostMapping
    public Result add(@RequestBody  @ApiParam(name = "User对象",value = "传入JSON数据",required = true) User user){
        //调用UserService实现添加User
        userService.add(user);
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /***
     * 根据ID查询User数据
     * @param id
     * @return
     */
    @ApiOperation(value = "User根据ID查询",notes = "根据ID查询User方法详情",tags = {"UserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true)
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Integer id){
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<User>(true,StatusCode.OK,"查询成功",user);
    }

    /***
     * 根据ID查询User数据  唐聪需求
     * @param id
     * @return
     */
    @ApiOperation(value = "User根据ID查询",notes = "根据ID查询User方法详情",tags = {"UserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @GetMapping("/findUser")
    public User findUserByID(Integer id){
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
       return user;
    }

    /***
     * 查询User全部数据
     * @return
     */
    @ApiOperation(value = "查询所有User",notes = "查询所User有方法详情",tags = {"UserController"})
    @GetMapping
    public Result<List<User>> findAll(){
        //

        //调用UserService实现查询所有User
        List<User> list = userService.findAll();
        return new Result<List<User>>(true, StatusCode.OK,"查询成功",list) ;
    }

    /**
     * 注册
     * @param file
     * @param user
     * @return
     */
    @PostMapping("/regist")
    @ResponseBody
    public Map regist(@RequestParam(value = "file",required = false) MultipartFile file, User user) {
        Map map=new HashMap();
            //判断用户是否存在
            User byName = userService.findByName(user.getName());
            if(byName!=null) {
                map.put("code",30001);
                map.put("msg","用户已存在");
                return  map;
            }
            //判断电话号码是否存在
            User bytelephone = userService.findBytelephone(user.getTelephone());
            if(bytelephone!=null) {
                map.put("code",30002);
                map.put("msg","手机号码已存在");
                return map;
            }
        try {
            //将加密后的密码存入数据库
            String pwdMD5 = code(user.getPassword());
            user.setPassword(pwdMD5);
            //存入图片
            FileUploadResult upload = aliyunossUtils.upload(file);
            String img = upload.getName();
            user.setHeadImg(img);
            //注册时间
            user.setCreatetime(new Date());
            userService.add(user);
            map.put("code",200);
            map.put("msg","注册成功！");
        } catch (Exception e) {
            map.put("code",500);
            map.put("msg","注册失败");
        }
        return map;
    }

    /**
     * md5加密方法
     * @param str
     * @return
     */
    private static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }



    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 通过账号和密码登录（携带user对象）
     * @param user
     * @return
     */
    @GetMapping("/loginWithPassword")
    public Result loginWithNameAndPwd(User user) {
        if (user == null) {
            return new Result(false,StatusCode.ERROR,"登录失败");
        }
        String name = user.getName();
        String password = user.getPassword();
        try {
            if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
                return new Result(false,StatusCode.ERROR,"账号或者密码不能为空");
            }
            if (userService.findByName(name) == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不匹配");
            }
            password=code(password);
            User findByNameAndPassword = userService.findByNameAndPassword(name,password);
            if (findByNameAndPassword == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不正确");
            } else {
                User byName = userService.findByName(name);
                if(byName.getHomeId()!=null){
                    Home home = homeService.selectByid(byName.getHomeId());
                    byName.setHome(home);
                }
                return new Result(false,StatusCode.OK,"登录成功",byName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,e.getMessage());
        }
    }
    @PostMapping("/attestation")
    @ResponseBody
    public ResultUtil attestation(@RequestBody Home home){
        home.setPropertyId(0);
        List<Village> village = villageService.selectByName(home.getAreaName());
        if(village.size()==0){
            ResultUtil resultUtil = ResultUtil.faild();
            resultUtil.setMsg("小区不存在，请重新输入");
            return resultUtil;
        }else {
            home.setAreaId(village.get(0).getId());
            try {
                homeService.addNewHome(home);
                System.out.println("插入成功，id："+home.getHomeId());
                User user = new User();
                user.setTelephone(home.getTelephone());
                user.setHomeId(home.getHomeId());
                user.setVillageId(village.get(0).getId());
                user.setCommunity(home.getAreaName());
                userService.updateHome(user);
                ResultUtil resultUtil = ResultUtil.success();
                User result = userService.findBytelephone(user.getTelephone());
                if(result.getHomeId()!=null){
                    Home home2 = homeService.selectByid(result.getHomeId());
                    result.setHome(home);
                }
                Map map = new HashMap();
                map.put("user",result);
                resultUtil.setResult(map);
                return resultUtil;
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.faild();
            }
        }
    }
    @GetMapping("/getuser")
    public ResultUtil getUser(String name){
        System.out.println("进来了进行查找用户");
        User user =userService.findByName(name);
        if (user!=null){
            Home home2 = homeService.selectByid(user.getHomeId());
            user.setHome(home2);
        }
        System.out.println(user.getName()+":"+user.getCommunity()+":"+user.getIsAttestation());
        ResultUtil resultUtil = ResultUtil.success();
        Map map = new HashMap();
        map.put("user",user);
        resultUtil.setResult(map);
        return resultUtil ;
    }





}
